package com.xgq.drink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgq.drink.entity.Cart;
import com.xgq.drink.entity.R;
import com.xgq.drink.entity.dto.CartItemDTO;
import com.xgq.drink.service.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cart")
@Tag(name = "购物车模块", description = "购物车管理接口")
public class CartController {

    @Autowired
    private ICartService cartService;
    @Autowired
    private IBrandService brandService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IDiscountInfoService discountInfoService;
    @Autowired
    private IAttributeProductService attributeProductService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public R addCartItem(@RequestBody Cart cart, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        cart.setUserId(Long.valueOf(userId));
        if(cartService.addCartItem(cart)){
            return RUtils.success("商品已添加到购物车");
        }else{
            return RUtils.success("添加失败");
        }
    }

    /**
     * 删除购物车中的商品
     */
    @DeleteMapping("/delete")
    public R deleteCartItem(@RequestParam Long cartId,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        //这里补充见检查逻辑
        if(cartService.deleteCartItem(cartId)){
           return RUtils.success("删除成功");
        }else{
           return RUtils.success("删除失败");
        }
    }

    /**
     * 修改购物车中的商品数量或属性
     */
    @PutMapping("/update")
    public R updateCartItem(@RequestBody Cart cart,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        //补充检查逻辑
        if(cartService.updateCartItem(cart)){
            return RUtils.success("更新成功");
        }else{
            return RUtils.success("更新失败");
        }
    }

    /**
     * 分页查询购物车商品
     */
    @GetMapping("/list")
    public R getCartItems(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String userId = jwtTokenUtil.getUserIdFromToken(token);
            IPage<Cart> carts = cartService.getCartItems(Long.valueOf(userId), page, size);
            // 同步查询商家信息和商品信息
            List<CartItemDTO> cartItemDTOs = carts.getRecords().stream()
                    .map(cart -> {
                        CartItemDTO dto = new CartItemDTO();
                        dto.setCart(cart);
                        dto.setBrand(brandService.getBrandInfo(cart.getBrandId()));
                        dto.setProduct(productService.getProductDetailById(cart.getProductId()));
                        dto.setAttributeProduct(attributeProductService.getById(cart.getAttributeId()));
                        dto.setDiscountInfos(discountInfoService.getDiscountsByProductId(cart.getProductId()));
                        return dto;
                    })
                    .collect(Collectors.toList());

            // 将 DTO 列表封装到 IPage 中
            IPage<CartItemDTO> cartItemDTOPage = new Page<>(carts.getCurrent(), carts.getSize(), carts.getTotal());
            cartItemDTOPage.setRecords(cartItemDTOs);

            return RUtils.success("获取成功", cartItemDTOPage);
        } catch(Exception e){
            return RUtils.fail("获取失败"+e);
        }
    }
    @PostMapping("/updateCartItem")
    public R updateCartItem(@RequestBody Cart request) {
        // 更新购物车中的优惠券选择
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cart_id", request.getCartId());
        queryWrapper.eq("discount_id", request.getDiscountId());
        cartService.update(queryWrapper);
        return RUtils.success("更新成功");
    }
}